/**
 * D5Power Studio FPower 2D MMORPG Engine
 * 第五动力FPower 2D 多人在线角色扮演类网页游戏引擎
 * 
 * copyright [c] 2010 by D5Power.com Allrights Reserved.
 */ 
package com.D5Power.Controler
{
	import com.D5Power.Objects.ControlActionObject;
	
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	

	/**
	 * Lua 脚本控制器
	 */ 
	public class BaseLuaControler
	{
		/**
		 * 控制目标，该目标必须是实现了LuaDispatch接口的对象
		 */ 
		protected var _obj:*;
		
		/**
		 * 创建一个Lua脚本控制器
		 */ 
		public function BaseLuaControler(obj:*)
		{
			_obj = obj;
		}
		
		/**
		 * 脚本的URL
		 */ 
		public function set scriptURL(file:String):void
		{
			var loader:URLLoader = new URLLoader();
			loader.dataFormat = URLLoaderDataFormat.BINARY; // 以二进制的方式加载文件
			loader.load(new URLRequest(file));
			loader.addEventListener(Event.COMPLETE,onComplate);
		}
		
		/**
		 *  加载脚本完成后，呼叫主函数运行脚本
		 */ 
		protected function onComplate(e:Event):void
		{
			var loader:URLLoader = e.target as URLLoader;
			loader.removeEventListener(Event.COMPLETE,onComplate);
			_obj.runLua(getCode(loader.data));
		}
		
		public static function getCode(s:String):String
		{
			var rawText:String = s.replace(/[<]\/P[>]/g, "\n"); // change all </P> to line returns
			rawText = rawText.replace(/<[a-zA-Z\/][^>]*>/g, ""); // strip all html
			
			var space:RegExp = /[ \t]/;
			
			// for each line
			var ret:String = "";
			var line:String;
			for each (line in rawText.split("\n"))
			{
				if (ret != "") // add line return if not first line
					ret = ret + "\n"
				
				// preserve beginning spaces
				for (var i:int = 0; i < line.length; i++)
				{
					if (space.test(line.charAt(i)))
						ret = ret + line.charAt(i)
					else
						break;
				}
				// use XML to transform any &quot; type escapes to raw text
				ret = ret + XML("<line>" + line + "</line>").text();
			}
			
			return ret;
		}
	}
}